/**
 * 资产
 * */
import React, { useState, useEffect, useMemo } from 'react';
import { Select, message, Tooltip } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import IconFont from '@/components/IconFont';
import { DynamicTable } from '@/pages/TurnoverSetting/EntrySetting/components';
import { getDeviceAll, postAccept } from '../../../services';

const { Option } = Select;

const SpanControl = React.forwardRef(({ value, assetType }, ref) => {
    const valueMemo = useMemo(() => value, [value]);
    const renderControl = useMemo(() => {
        if (assetType && typeof value === 'number') {
            return <span ref={ref}>{value ? '消耗品' : '固定资产'}</span>;
        }
        return <span ref={ref}>{valueMemo}</span>;
    }, [assetType, value, ref, valueMemo]);
    return renderControl;
});

const DeviceConfigTable = ({ entryPersonnelCode, canAction, form, assetList }) => {
    const [dataSource, setDataSource] = useState([]);
    const [operatorId, setOperatorId] = useState(undefined);
    // 获取可选资产列表
    const deviceParam = { entryPersonnelCode, assetCategory: 'Administrative' };
    const { data: propertyList = [], run: fetchProperty } = useRequest(() => getDeviceAll(deviceParam), {
        manual: true,
        ...defaultFormatResult
    });
    // 获取可选资产列表
    const { run: submitProperty } = useRequest(id => postAccept(id), {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                message.success(msg);
                // 改状态
                const newData = form.getFieldValue('assetList');
                const index = newData.findIndex(item => item.id === operatorId);
                newData[index].isAchieve = 1;
                setDataSource([...newData]);
            } else {
                message.error(msg);
            }
        }
    });

    // 数据处理
    const formatModelData = (assetCode, modelCode) => {
        if (assetCode && modelCode) {
            const deviceData = propertyList.find(item => item.assetCode === assetCode);
            const modelData = deviceData?.assetModelList.find(item => item.modelCode === modelCode);
            if (modelData) {
                return modelData?.assetNumber || '';
            }
            return '';
        }
        return '';
    };
    // 型号
    const formatDeviceData = data => {
        if (typeof data === 'string') {
            const device = propertyList?.find(item => item.assetCode === data);
            if (device) {
                return device.assetModelList || [];
            }
            return [];
        }
        return [];
    };
    // 接收资产
    const handleAccept = record => {
        submitProperty(record.id);
        setOperatorId(record.id);
    };

    // 操作
    const handleOperator = (record, index, methods) => {
        if (record.id) {
            if (record.isAchieve === 0 && canAction && record.entryStatus !== 4) {
                // entryStatus 为行政准备，当前环节下不可以接收
                return (
                    <Tooltip title="接收">
                        <IconFont icon="iconwuzijieshou" isButton onClick={() => handleAccept(record, index)} />
                    </Tooltip>
                );
            }
            return (
                <Tooltip title="已接收">
                    <IconFont icon="iconwuzijieshou" isButton disabled style={{ color: '#E8E8E8' }} />
                </Tooltip>
            );
        }
        return (
            <Tooltip title="删除">
                <IconFont
                    icon="iconDeleteIcon"
                    isButton
                    onClick={() => {
                        if (canAction) {
                            methods.remove(index);
                        }
                    }}
                />
            </Tooltip>
        );
    };

    // 处理资产名称;
    const handleSelectAssetCode = (text, fieldDecorator, setFieldsValue, record) => {
        if (record.id) {
            return <span>{record.assetName}</span>;
        }
        return fieldDecorator('assetCode', {
            initialValue: text,
            rules: [
                {
                    required: !record.id,
                    message: '请选择'
                }
            ]
        })(
            <Select
                style={{ width: '120px' }}
                placeholder="请选择"
                getPopupContainer={triggerNode => triggerNode.parentElement}
                onSelect={selectValue => {
                    const option = propertyList.find(item => item.assetCode === selectValue) || {};
                    const { assetName, assetType, required = '1', assetCode } = option;
                    const assetNumber = formatModelData(assetCode, selectValue);
                    setFieldsValue({
                        modelCode: undefined,
                        assetName,
                        assetType,
                        required,
                        assetNumber,
                        entryStatus: '4'
                    });
                }}
                disabled={!canAction}
            >
                {propertyList &&
                    propertyList.map(item => (
                        <Option value={item.assetCode} key={item.assetCode}>
                            {item.assetName}
                        </Option>
                    ))}
            </Select>
        );
    };
    // 选择资产型号
    const handleSelectModelCode = (text, fieldDecorator, setFieldValue, getFieldValue, record) => {
        if (record.id) {
            return <span>{record.modelName}</span>;
        }
        const assetCode = getFieldValue('assetCode');

        const deviceData = propertyList.find(item => item.assetCode === assetCode);
        const deviceDataLen = deviceData?.assetModelList.length;
        if (deviceDataLen > 0) {
            return fieldDecorator('modelCode', {
                initialValue: text,
                rules: [
                    {
                        required: !record.id && deviceDataLen > 0,
                        message: '请选择'
                    }
                ]
            })(
                <Select
                    style={{ width: '120px' }}
                    onSelect={() => {
                        const assetNumber = formatModelData(getFieldValue('assetCode'), getFieldValue('modelCode'));
                        setFieldValue('assetNumber', assetNumber);
                    }}
                    placeholder="请选择"
                    disabled={!canAction}
                >
                    {formatDeviceData(getFieldValue('assetCode')).map(item => (
                        <Option value={item.modelCode} key={item.modelCode}>
                            <Tooltip title={item.modelName}>{item.modelName}</Tooltip>
                        </Option>
                    ))}
                </Select>
            );
        }
        return <span>-</span>;
    };

    useEffect(() => {
        setDataSource([...assetList]);
    }, [assetList]);

    useEffect(() => {
        fetchProperty();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const columns = [
        {
            title: '资产名称',
            dataIndex: 'assetCode',
            width: 180,
            render: ({ text, fieldDecorator, setFieldsValue, record }) =>
                handleSelectAssetCode(text, fieldDecorator, setFieldsValue, record)
        },
        {
            title: '资产型号',
            dataIndex: 'modelCode',
            width: 240,
            render: ({ text, fieldDecorator, setFieldValue, getFieldValue, record }) => (
                <>{handleSelectModelCode(text, fieldDecorator, setFieldValue, getFieldValue, record)}</>
            )
        },
        {
            title: '资产类型',
            dataIndex: 'assetType',
            width: 100,
            render: ({ text, fieldDecorator }) => (
                <>
                    {fieldDecorator('assetType', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '请选择'
                            }
                        ]
                    })(<SpanControl assetType />)}
                </>
            )
        },
        {
            title: '需求数量',
            dataIndex: 'required',
            width: 150,
            render: ({ text, fieldDecorator }) => (
                <>
                    {fieldDecorator('required', {
                        initialValue: text
                    })(<span>1</span>)}
                </>
            )
        },
        {
            title: '资产编号',
            dataIndex: 'assetNumber',
            width: 180,
            render: ({ text, fieldDecorator, getFieldValue }) => (
                <>
                    {fieldDecorator('assetNumber', {
                        initialValue: text
                    })(<span>{text || formatModelData(getFieldValue('assetCode'), getFieldValue('modelCode'))}</span>)}
                </>
            )
        },
        // {
        //     title: '可用库存',
        //     dataIndex: 'availableStock',
        //     width: '8%',
        //     render: () => <span>-</span>
        // },
        // {
        //     title: '总库存',
        //     dataIndex: 'sumStock',
        //     width: '8%',
        //     render: () => <span>-</span>
        // },
        {
            title: '状态',
            dataIndex: 'isAchieve',
            width: 150,
            render: ({ text, fieldDecorator, record }) => (
                <>
                    {fieldDecorator('isAchieve', {
                        initialValue: text
                    })(
                        <span>
                            {record.id ? (
                                <span>
                                    {text === 1 ? (
                                        <span style={{ color: '#000' }}>已接收</span>
                                    ) : (
                                        <span style={{ color: '#5590F6' }}>未接收</span>
                                    )}
                                </span>
                            ) : (
                                ''
                            )}
                        </span>
                    )}
                </>
            )
        },
        {
            title: '操作',
            dataIndex: 'operator',
            width: 100,
            render: ({ text, fieldDecorator, index, record, methods }) => (
                <>
                    {fieldDecorator('operator', {
                        initialValue: text
                    })(handleOperator(record, index, methods))}
                </>
            )
        },
        {
            dataIndex: 'id',
            hide: true // 不展示, 但是需要记录的数据
        },
        {
            dataIndex: 'entryStatus',
            hide: true // 不展示, 但是需要记录的数据
        },
        {
            dataIndex: 'assetName',
            hide: true
        },
        {
            dataIndex: 'modelName',
            hide: true
        }
    ];

    return (
        <>
            <p>请确认电脑及其配套资产已接收，所有资产已准备妥当：</p>
            <DynamicTable form={form} initialValue={dataSource || []} fieldName="assetList" columns={columns} />
        </>
    );
};
export default React.forwardRef(DeviceConfigTable);
